class Fetcher < ActiveRecord::Base
  include StorageSystem
  
  belongs_to :replica
  
  Replicate = 'put'
  Fetch     = 'get'
  Delete    = 'delete'
  
  # Returns a Replica System Object
  def replica_system
    self.replica.replica_system
  end
  
  # Returns a Replica Object
  def main_replica
    self.replica.audio_asset.find_main_essence
  end
  
  def self.find_get_fetchers
    Fetcher.find :all, :conditions => { :done => false, :action => Fetcher::Fetch }
  end
  
  def self.find_put_fetchers
    Fetcher.find :all, :conditions => { :done => false, :action => Fetcher::Replicate }
  end
  
  
  def fetch
    puts "Fetching " + self.replica.audio_asset.name
  end
  
  def replicate  
    begin
      case self.replica_system.protocol
      when ReplicaSystem::FTP
        FtpReplication.put(self)
      when ReplicaSystem::SMB
        SmbReplication.put(self)
      when ReplicaSystem::HTTP
        HttpReplication.put(self)
      end
    rescue FileNotStoredException
      # TODO: log error and change fetcher status
    end

    # change fetcher status
    return true
  end
end